package com.ytkj.digitalConstruction.service.permission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ytkj.digitalConstruction.dao.permission.PermissionMapper;
import com.ytkj.digitalConstruction.dao.permission.RolePermissionMapper;
import com.ytkj.digitalConstruction.entity.permission.Permission;
import com.ytkj.digitalConstruction.entity.permission.RolePermission;
import com.ytkj.digitalConstruction.entity.role.Role;
import com.ytkj.digitalConstruction.enums.PermissionType;
import com.ytkj.digitalConstruction.service.role.RoleService;

/**
 * 权限业务处理类
 * 
 * @author Pete
 * @Date 2017年12月7日
 */
@Service
public class PermissionService {

	@Autowired
	private RolePermissionMapper rolePermissionMapper;

	@Autowired
	private PermissionMapper permissionMapper;

	@Autowired
	private RoleService roleService;

	/**
	 * 获取用户权限ID集合
	 * 
	 * @param userId
	 * @return
	 */
	public Map<PermissionType, List<Permission>> getUserOperations(int userId) {
		List<Role> roles = roleService.getUserRoles(userId);
		Map<PermissionType, List<Permission>> map = new HashMap<>();
		Map<PermissionType, Map<Integer, Permission>> m = new HashMap<>();
		Map<Integer, Permission> ps = null;
		for (Role r : roles) {
			Map<PermissionType, List<Permission>> pm = getRoleOperations(r.getRoleId());
			for (Entry<PermissionType, List<Permission>> e : pm.entrySet()) {
				PermissionType type = e.getKey();
				ps = (ps = m.get(type)) != null ? ps : new HashMap<>();
				for (Permission p : e.getValue()) {
					ps.put(p.getId(), p);
				}
			}
		}
		for (Entry<PermissionType, Map<Integer, Permission>> e : m.entrySet()) {
			PermissionType type = e.getKey();
			List<Permission> permissions = e.getValue().values().stream().collect(Collectors.toList());
			map.put(type, permissions);
		}
		return map;
	}

	/**
	 * 获取角色权限集合
	 * 
	 * @param roleId
	 * @return
	 */
	public Map<PermissionType, List<Permission>> getRoleOperations(int roleId) {
		List<RolePermission> rolePermissions = rolePermissionMapper.selectByRoleId(roleId);
		Map<PermissionType, List<Permission>> map = new HashMap<>();
		List<Permission> list = null;
		for (RolePermission rp : rolePermissions) {
			Permission p = permissionMapper.selectByPrimaryKey(rp.getPermissionId());
			if (p.getPermissionType() == PermissionType.MENU.getType()) {
				list = (list = map.get(PermissionType.MENU)) != null ? list : new ArrayList<>();
			} else {
				list = (list = map.get(PermissionType.FLOW)) != null ? list : new ArrayList<>();
			}
			list.add(p);
		}
		return map;
	}

}
